package com.example.carapplication.entry;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SignUpCallback;
import com.example.carapplication.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener {
	Button btn_register;
	EditText RUserName;
	EditText RPassword;

	String username;
	String password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
		btn_register.setOnClickListener(this);
	}

	private void initView() {
		// TODO Auto-generated method stub
		RUserName = (EditText) findViewById(R.id.RUserName);
		RPassword = (EditText) findViewById(R.id.RPasssword);

		btn_register = (Button) findViewById(R.id.RBtn);
	}

	@Override
	public void onClick(View v) {

		username = RUserName.getText().toString();
		password = RPassword.getText().toString();

		AVUser user = new AVUser();
		user.setUsername(username);
		user.setPassword(password);

		judge();
		user.signUpInBackground(new SignUpCallback() {

			@Override
			public void done(AVException arg0) {
				// TODO Auto-generated method stub
				if (arg0 == null) {
					Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
					Intent i = new Intent();
					i.setClass(RegisterActivity.this, LoginActivity.class);
					startActivity(i);
					finish();
				} else {
					Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();

				}
			}
		});
	}

	private void judge() {
		// TODO Auto-generated method stub
		if (username.length() >= 10) {
			Toast.makeText(RegisterActivity.this, "用户名不能超过十位", Toast.LENGTH_SHORT).show();
			return;
		} else if (username.length() == 0) {
			Toast.makeText(RegisterActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
			return;
		} else if (password.length() > 16) {
			Toast.makeText(RegisterActivity.this, "密码长度不能超过十六位", Toast.LENGTH_SHORT).show();
			return;
		} else if (username.equals(password)) {
			Toast.makeText(RegisterActivity.this, "用户名和密码不能相同", Toast.LENGTH_SHORT).show();
			return;
		}
	}

}
